package com.zhenyi.wumian.ws;

import com.jfinal.kit.Ret;
import com.utils.PathUtils;
import com.zhenyi.websocket.core.wumain.ChannelGroups;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class Handler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

	private FileWriter writer = new FileWriter(PathUtils.getFile("wm", "count.txt"));
	private FileReader reader = new FileReader(PathUtils.getFile("wm", "count.txt"));

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

		String text = msg.text();
		if ("click".equals(text)) {
			String countStr = reader.readString();
			Long count = Long.parseLong(countStr) + 1L;
			writer.write(String.valueOf(count));
			return;
		}
		System.out.println(text);
		// Ret ret = Ret.by("status", 200);
		// ctx.channel().writeAndFlush(new
		// TextWebSocketFrame(ret.toJson()));
		// final FullHttpRequest request = (FullHttpRequest) msg;
		// final HttpMethod method = request.method();
		// final String uri = request.uri();
		// System.out.println(uri);
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		System.out.println("handlerAdded " + ctx.name());
		super.handlerAdded(ctx);
		ChannelGroups.add(ctx.channel());
		Ret ret = Ret.by("status", 201);
		ret.set("dir", "add");
		ChannelGroups.broadcast(new TextWebSocketFrame(ret.toJson()));
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		System.out.println("handlerRemoved");
		super.handlerRemoved(ctx);
		ChannelGroups.discard(ctx.channel());
		Ret ret = Ret.by("status", 201);
		ret.set("dir", "remove");
		ChannelGroups.broadcast(new TextWebSocketFrame(ret.toJson()));
	}

}
